package com.zhihaoliang.moshi.biz.adapter

import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonQualifier
import com.squareup.moshi.Moshi
import com.squareup.moshi.ToJson
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.zhihaoliang.moshi.util.log


/**
 * @author 支豪亮
 * @date 2023/1/28 17:21
 * @des 颜色的设置
 */
class ColorAdapter {

    @ToJson
    fun toJson(@HexColor rgb: Int): String = String.format("#%06x", rgb)

    @FromJson
    @HexColor
    fun fromJson(rgb: String): Int = Integer.parseInt(rgb.substring(1), 16)
}

@Retention(AnnotationRetention.RUNTIME) @JsonQualifier annotation class HexColor

internal class Rectangle {
    var width = 0
    var height = 0

    @HexColor var color = 0
    override fun toString(): String {
        return String.format("%dx%d #%06x ->%d", width, height, color,color)
    }
}

fun customQualifier(){
    val data = """
        {
            "color":"#ff0000",
            "height":768,
            "width":1024
        }
    """.trimIndent()

    val moshi = Moshi.Builder().add(ColorAdapter()).add(KotlinJsonAdapterFactory()).build()
    val jsonAdapter = moshi.adapter(
        Rectangle::class.java
    )

    val rectangle: Rectangle? = jsonAdapter.fromJson(data)
    log(rectangle.toString())
}